package com.gistmap.sideline.service;

import com.gistmap.sideline.entity.User;
import com.gistmap.sideline.util.CodeCache;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.jasypt.util.text.BasicTextEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 完整的激活流程
 * （前端定位）
 * 发送带有可解密的字符参数 -> 用户点击跳转前端静态页面 -> 拿到参数再访问解密确认接口
 * （后端定位）
 * 即给用户发送的URL为ip/域名+接口路径+参数 -> 用户点击进行服务端验证 -> 跳到项目内写好的html/重定向到真实域名
 */
@Slf4j
@Service
public class MailService {

    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private UserService userService;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${spring.mail.username}")
    private String sender;

    public void sendTemplateMail(String to, String name, Long id){
        MimeMessage message = null;
        try {
            message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(sender);
            helper.setTo(to);
            helper.setSubject("主题：模板邮件");

            String code = encode(id);

            // 邮件中的参数
            Map<String, Object> model = new HashMap<>();
            model.put("url", "wwww.xxxx.com/xx/xx?secret=" + code);
            model.put("name", name);

            Template template = freeMarkerConfigurer.getConfiguration().getTemplate("mail.html");
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
            helper.setText(html, true);

            // 将用户的激活码放到缓存保存1天
            CodeCache.INSTANCE.put(id, code);

        } catch (Exception e) {
            e.printStackTrace();
        }
        mailSender.send(message);
    }

    /**
     * 生成激活邮件后的参数
     * @param id
     * @return
     */
    public String encode(Long id){
        String timestamp = String.valueOf(new Date().getTime()/1000);
        System.out.println(timestamp);
        String code = timestamp + id + RandomStringUtils.randomAlphabetic(10);
        System.out.println(code);
        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        textEncryptor.setPassword(code);
        String result = textEncryptor.encrypt("hasai");
        System.out.println(result);
        return result;
    }

}
